export default {
	namespaced: true,

	state: () => ({
		//{goods_id,goods_name,goods_count,goods_small-logo,goods_state}
		// 使用本地的cart数据，没有则返回0
		cart: JSON.parse(uni.getStorageSync('cart')||'[]'),
	}),

	mutations: {
		addToCart(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			// commit()方法来修改state数据，使用m_cart模块的savaToStorage方法
			this.commit('m_cart/savaToStorage')
		},
		savaToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		//更新购物车中的商品勾选状态
		updateGoodsState(state,goods){
		  const findResult =state.cart.find(
			x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/savaToStorage')
			}
		},
		//更新商品数量
		updateGoodsCount(state,goods){
			//根据goods_id查询购物车中对应的商品信息对象
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/savaToStorage')
			}
		},
		//根据id从购物车中删除对应的商品信息
		removeGoodsById(state,goods_id){
			//filter方法来过滤该id的商品
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			this.commit('m_cart/savaToStorage')
		},
		//更新购物车所有商品勾选状态
		updateAllGoodsState(state,newState){
			state.cart.forEach(x => x.goods_state = newState)
			this.commit('m_cart/savaToStorage')
		}
	},
	getters: {
		total(state) {
			// let c = 0
			// state.cart.forEach(x => c += x.goods_count)
			// return c
			return state.cart.reduce((total,item)=>total += item.goods_count,0)
		},
		checkedCount(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item) => total+=item.goods_count,0)
		},
		checkedGoodsAmount(state){
			//使用filter过滤掉没有勾选的商品，再用reduce方法将勾选的商品数量*单价后进行累加
			return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
		}
	}





}
